package com.medical.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.medical.core.result.PageResult;
import com.medical.core.result.Result;
import com.medical.system.listener.excel.UserImportListener;
import com.medical.system.model.entity.SysUser;
import com.medical.system.model.form.UserForm;
import com.medical.system.model.query.UserPageQuery;
import com.medical.system.model.vo.UserExportVO;
import com.medical.system.model.vo.UserImportVO;
import com.medical.system.model.vo.UserInfoVO;
import com.medical.system.model.vo.UserPageVO;
import com.medical.system.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@Tag(name = "01.用户接口")
@RestController
@RequestMapping("/api/v1/user")
@RequiredArgsConstructor
public class SysUserController {

    private final SysUserService userService;

    @Operation(summary = "用户列表分页")
    @GetMapping("/page")
    public PageResult<UserPageVO> getUserPage(@ParameterObject UserPageQuery userPageQuery) {
        return PageResult.success(userService.getUserPage(userPageQuery));
    }

    @Operation(summary = "新增用户")
    @PostMapping
    @SaCheckPermission("sys:user:add")
    public Result saveUser(@RequestBody @Valid UserForm userForm) {
        return Result.judge(userService.saveUser(userForm));
    }

    @Operation(summary = "用户表单详情")
    @GetMapping("/{userId}/form")
    public Result<UserForm> getUserForm(@Parameter(description = "用户ID") @PathVariable Long userId) {
        UserForm userForm = userService.getUserFormData(userId);
        return Result.success(userForm);
    }

    @Operation(summary = "修改用户信息")
    @PutMapping("/{userId}")
    @SaCheckPermission("sys:user:edit")
    public Result updateUser(@Parameter(description = "用户ID") @PathVariable Long userId,
                             @RequestBody @Validated UserForm userForm) {
        return Result.judge(userService.updateUser(userId, userForm));
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{ids}")
    @SaCheckPermission("sys:user:delete")
    public Result deleteUsers(@Parameter(description = "用户ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        return Result.judge(userService.deleteUsers(ids));
    }

    @Operation(summary = "修改用户密码")
    @PatchMapping(path="/{userId}/password", consumes="application/json")
    @SaCheckPermission("sys:user:reset_pwd")
    public Result updatePassword(@Parameter(description = "用户ID") @PathVariable Long userId,
                                 @Parameter(description = "用户密码") @RequestParam  String password) {
        return Result.judge(userService.updatePassword(userId, password));
    }

    @Operation(summary = "修改用户状态")
    @PatchMapping("/{userId}/status")
    @SaCheckPermission("sys:user:update_status")
    public Result updateUserStatus(@Parameter(description = "用户ID") @PathVariable Long userId,
                                   @Parameter(description = "用户状态（1：启用；0：禁用）") @RequestParam(required = true)  Integer status) {
        return Result.judge(userService.update(new LambdaUpdateWrapper<SysUser>()
                .eq(SysUser::getId, userId)
                .set(SysUser :: getStatus, status)));
    }

    @Operation(summary = "获取当前登录用户信息")
    @GetMapping("/me")
    public Result<UserInfoVO> getCurrentUserInfo() {
        return Result.success();
    }

    @Operation(summary = "用户导入模板下载")
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        String fileName = "用户导入模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        String fileClassPath = "excel-templates" + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);
        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
        excelWriter.finish();
    }

    @Operation(summary = "导入用户")
    @PostMapping("/import")
    public Result importUser(@Parameter(description = "部门ID") Long deptId, MultipartFile file) throws IOException {
        UserImportListener listener = new UserImportListener(deptId);
        EasyExcel.read(file.getInputStream(), UserImportVO.class, listener).sheet().doRead();
        return Result.success(listener.getMsg());
    }

    @Operation(summary = "导出用户")
    @GetMapping("/export")
    public void exportUser(UserPageQuery queryParams, HttpServletResponse response) throws IOException {
        String fileName = "用户列表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        List<UserExportVO> exportUserList = userService.listExportUsers(queryParams);
        EasyExcel.write(response.getOutputStream(), UserExportVO.class).sheet("用户列表")
                .doWrite(exportUserList);
    }

    @Operation(summary = "获取用户个人中心信息")
    @GetMapping("/profile")
    public Result getUserProfile() {
        return Result.success(userService.getUserProfile());
    }
}
